package com.xuecheng.content.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.io.BaseEncoding;
import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.CourseBaseDto;
import com.xuecheng.commons.model.dto.CourseDto;
import com.xuecheng.commons.model.dto.PageRequest;
import com.xuecheng.commons.model.vo.CourseBaseVo;
import com.xuecheng.commons.model.vo.PageResponseResult;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.content.config.MinioTemplate;
import com.xuecheng.content.domain.CourseBase;
import com.xuecheng.content.domain.Teachplan;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.service.TeachplanService;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.*;

/**
 * <p>
 * 课程基本信息 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-12-03
 */
@Service
public class CourseBaseServiceImpl extends ServiceImpl<CourseBaseMapper, CourseBase> implements CourseBaseService {
   @Autowired
   private MinioTemplate minioTemplate;
    //分页+条件查询
    @Override
    public ResponseResult<CourseBaseVo> findByPage(PageRequest pageRequest, CourseDto dto) {
        // 1.构建分页
        Page<CourseBase> page = new Page<>(pageRequest.getPageNo(),pageRequest.getPageSize());
      /*  // 2.构建条件
        LambdaQueryWrapper<CourseBase> lq = new LambdaQueryWrapper<>();
        // 2-1 课程名称
        lq.like(StrUtil.isNotEmpty(dto.getCourseName()),CourseBase::getName,dto.getCourseName());
        // 2-2 课程状态
        lq.eq(StrUtil.isNotEmpty(dto.getAuditStatus()),CourseBase::getAuditStatus,dto.getAuditStatus());
        // 2-2 课程类型
        lq.eq(StrUtil.isNotEmpty(dto.getTeachmode()),CourseBase::getTeachmode,dto.getTeachmode());
        // 3.分页查询
        page = this.page(page, lq);
        // 4.转vo
        List<CourseBase> records = page.getRecords();
        ArrayList<CourseBaseVo> courseBaseVos = new ArrayList<>();
        for (CourseBase record : records) {
            CourseBaseVo courseBaseVo = BeanHelper.copyProperties(record, CourseBaseVo.class);
            courseBaseVos.add(courseBaseVo);
        }*/
        //================================== 2.构建条件（链式编程）
        page = this.lambdaQuery()
                .like(StrUtil.isNotEmpty(dto.getCourseName()), CourseBase::getName, dto.getCourseName()) // 课程名称
                .eq(StrUtil.isNotEmpty(dto.getAuditStatus()), CourseBase::getAuditStatus, dto.getAuditStatus()) // 课程状态
                .eq(StrUtil.isNotEmpty(dto.getTeachmode()), CourseBase::getTeachmode, dto.getTeachmode()) // 课程类型
                .page(page); // 3.分页查询

        // 4.转vo
        List<CourseBaseVo> courseBaseVos = BeanHelper.copyWithCollection(page.getRecords(), CourseBaseVo.class);
        // 5.返回结果
        return PageResponseResult.okResult(page.getTotal(),courseBaseVos);
    }
    @Autowired
    private TeachplanService teachplanService;
    //新增课程
    @Override
    public ResponseResult<Map> insert(CourseBaseDto dto) {
        //校验前端参数
        if (!StrUtil.isAllNotEmpty(dto.getName(),dto.getTags()
                ,dto.getMt(),dto.getSt(),dto.getDescription()
                ,dto.getCharge(),dto.getPic(),dto.getGrade()
                ,dto.getUsers(),dto.getTeachmode()
                )) {
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        //dto转为CourseBase
        CourseBase courseBase = BeanHelper.copyProperties(dto, CourseBase.class);
        //补全课程信息
        courseBase.setAuditStatus(CourseConstants.AUDIT_UNPAST_STATUS); // 未提交课程状态
        courseBase.setPlanNum(0); // 课程小节数量
        courseBase.setCreateDate(new Date()); // 课程新增时间
        //保存到数据库
        boolean save = this.save(courseBase);
        if (save==false){
            throw new BusinessException(ErrorCode.ADDEERROR);
        }
        // 5.初始化一级大纲 （预留）
        Teachplan teachplan = new Teachplan();
        teachplan.setPname(courseBase.getName());// 一级大纲名称（课程信息名称）
        teachplan.setParentid(0L);// 一级大纲父节点id为0
        teachplan.setGrade(1); // 一级
        teachplan.setDescription(courseBase.getDescription());// 课程介绍
        teachplan.setCourseId(courseBase.getId());// 课程id
        teachplan.setCreateDate(new Date()); // 创建时间
        teachplanService.save(teachplan);


        //返回课程id
        Map map = new HashMap();
        map.put("courseBaseId", courseBase.getId());
        return ResponseResult.okResult(map);

    }
    //课程修改
    @Override
    public ResponseResult<Map> updateCourse(CourseBaseDto dto) {
        //校验前端参数
        if (!StrUtil.isAllNotEmpty(dto.getName(),dto.getTags()
                ,dto.getMt(),dto.getSt(),dto.getDescription()
                ,dto.getCharge(),dto.getPic(),dto.getGrade()
                ,dto.getUsers(),dto.getTeachmode()
        )) {
            throw new BusinessException(ErrorCode.DATAERROR);
        }
        CourseBase oldCourseBase = this.getById(dto.getId());
        //校验课程状态（已发布的课程不能修改）
        if (StrUtil.equals(oldCourseBase.getAuditStatus(), CourseConstants.AUDIT_PUBLISHED_STATUS)) {
            // 已发布（上架）课程，不能改
            throw new BusinessException(ErrorCode.MEDIABINDERROR);
        }
        CourseBase courseBase = BeanHelper.copyProperties(dto, CourseBase.class);
        //重置课程状态为未提交 需要重新审核
        courseBase.setAuditStatus(CourseConstants.AUDIT_UNPAST_STATUS);//重置状态未提交
        //保存到数据库
        boolean update = this.updateById(courseBase);
        if (update==false){
            throw new BusinessException(ErrorCode.ADDEERROR);
        }
        // 5.更新课程计划（一级大纲）
        // 5-1 查询对应的一级大纲 select * from tb_teachplan where course_id = 47 and grade =1
        Teachplan oneTeachplan = teachplanService.lambdaQuery()
                .eq(Teachplan::getCourseId, courseBase.getId())
                .eq(Teachplan::getGrade, 1).one();
        // 5-2 修改名称和介绍
        oneTeachplan.setPname(courseBase.getName());
        oneTeachplan.setDescription(courseBase.getDescription());
        // 5-3 更新数据库
        teachplanService.updateById(oneTeachplan);

        //返回课程id
        Map map = new HashMap();
        map.put("courseBaseId", courseBase.getId());
        return ResponseResult.okResult(map);
    }
    //课程删除
    @Transactional // 一定要添加事务
    @Override
    public ResponseResult deleteCourseBase(Long courseId) {
        // 1.校验课程状态
        // 1-1 根据id查询课程
        CourseBase courseBase = this.getById(courseId);
        // 1-2 判断是否已发布
        if (StrUtil.equals(CourseConstants.AUDIT_PUBLISHED_STATUS,courseBase.getAuditStatus())) {
            throw new BusinessException(ErrorCode.DELETEERROR);
        }
        // 该课程下有 1 2 3级不允许删除
        Long count = teachplanService.lambdaQuery()
                .eq(Teachplan::getCourseId, courseId).count();
        if (count > 1) { // 超过一条有二级或者三级
            throw new BusinessException(ErrorCode.DELETEERROR);
        }

        // 只有1级的是可以删除的
        LambdaQueryWrapper<Teachplan> lq = new LambdaQueryWrapper<>();
        lq.eq(Teachplan::getCourseId,courseId);
        teachplanService.remove(lq);

        // 2.删除课程
        boolean isSuccess = this.removeById(courseId);
        if (isSuccess==false) {
            throw new BusinessException(ErrorCode.DELETEERROR);
        }

        String pic = courseBase.getPic();
        minioTemplate.remove(pic);
        // 3.返回删除成功  状态码：200
        return ResponseResult.okResult();

    }

}
